package com.isoft.game.common.filter;

import com.alibaba.fastjson.JSONObject;
import com.isoft.game.sys.user.entity.User;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by lcy on 17/4/6.
 */
public class AccessFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse)servletResponse;
        httpResponse.setContentType("UTF-8");
        httpResponse.setContentType("text/html;charset=UTF-8");
        HttpServletRequest httpRequest = ((HttpServletRequest)servletRequest);
        String url = httpRequest.getRequestURI();
        if(null != url){
            if(inBkFilterMapping(url,httpRequest.getContextPath())){
                Object user = httpRequest.getSession().getAttribute("user");
				 /*authentication*/
                if(null == user || !(user instanceof User)){
					 /*判断是否为ajax 请求*/
                    String requestType =(String) httpRequest.getHeader("X-Requested-With");
                    if (requestType != null && requestType.equals("XMLHttpRequest")) {
                        try{
                            JSONObject json = new JSONObject();
                            json.put("success", false);
                            json.put("message", "当前未登录,不能操作");
                            PrintWriter pw = servletResponse.getWriter();
                            pw.print(json.toString());
                            pw.close();
                        }catch (Exception e) {
                            Logger.getLogger(this.getClass()).error(e.getMessage());
                        }
                    }
                    else
                        httpResponse.sendRedirect(httpRequest.getContextPath()+"/view/background/login");
                    return ;
                }
                /*authorization*/
                /*if(!isAuthorization(url,user,httpRequest.getContextPath())){
                     //判断是否为ajax 请求
                    String requestType =(String) httpRequest.getHeader("X-Requested-With");
                    if (requestType != null && requestType.equals("XMLHttpRequest")) {
                        try{
                            JSONObject json = new JSONObject();
                            json.put("success", false);
                            json.put("message", "当前用户未授权,不能操作");
                            PrintWriter pw = servletResponse.getWriter();
                            pw.print(json.toString());
                            pw.close();
                        }catch (Exception e) {
                            Logger.getLogger(this.getClass()).error(e.getMessage());
                        }
                    }
                    else
                        httpResponse.sendRedirect(httpRequest.getContextPath()+"/common_include/error/403.jsp");
                    return ;
                }*/
            }
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }


    /**
     * 是否授权
     * @param url
     * @param user
     * @return
     */
    private boolean isAuthorization(String url, Object user,String contextPath) {
        //pass
        if(url.startsWith(contextPath+"/view/error/"))
            return true;
        if(url.startsWith(contextPath+"/view/login/login"))
            return true;
        //no pass
        User vdUser = (User)user;
        boolean flag = false;
        /*if(null != vdUser && null != vdUser.getMenuList() && 0 < vdUser.getMenuList().size()){
            for (VdMenu menu : vdUser.getMenuList()) {
                if(null != menu.getMenuUrl() && url.startsWith(contextPath + menu.getMenuUrl())){
                    flag = true;
                    break;
                }
            }
        }*/
        return  flag;
    }


    /**
     * 后台拦截
     * @param url
     * @return
     */
    private boolean inBkFilterMapping(String url,String contextPath){
        //登录请求不验证
        if(url.startsWith(contextPath+"/view/background/login"))
            return false;
            //todo 只拦截 管理端  再进行设计
        if(url.startsWith(contextPath+"/login/loginValidate"))
            return false;
        else if(url.endsWith(".gif"))
            return false;
        //String[] urls = url.split("/");
        //return (urls.length > 3 && "admin".equals(urls[2]));
        return true;
    }

    @Override
    public void destroy() {

    }
}
